<template>
  <base-page-view class-name="page-container go-bi-xuan">
    <view class="sticky-wrapper">
      <!-- 分类 -->
      <horizontal-list v-if="categoryList.length" list-name="category" :list="categoryList" @itemClick="categoryClick">
        <template v-slot="{item}">
          <view class="title">{{ item.title }}</view>
        </template>
      </horizontal-list>
      <!-- tag -->
      <horizontal-list v-if="tagList.length" list-name="tag" :list="tagList" @itemClick="tagClick">
        <template v-slot="{item}">
          <view class="title">{{ item.title }}</view>
        </template>
      </horizontal-list>
    </view>

    <template v-if="url">
      <view v-if="activityData.modules && activityData.modules.length" class="url-content">
        <custom-modules :list="activityData.modules" :scroll-top="scrollTop" />
      </view>
      <template v-if="activityData.footer_tabs && activityData.footer_tabs.content_list && activityData.footer_tabs.content_list.length && (activityData.footer_tabs.screenToShow === 0 || showFooterBar)">
        <!-- 占位用的-开始 -->
        <view class="footer-tab hidden">
          <view v-for="(item, index) in activityData.footer_tabs.content_list" :key="index" class="footer-tab-item">
            <b-image :src="item.pic" mode="widthFix" />
          </view>
        </view>
        <!-- 占位用的-结束 -->
        <footer-bar>
          <view class="footer-tab">
            <view v-for="(item, index) in activityData.footer_tabs.content_list" :key="index" class="footer-tab-item" @click="handleFooterTabClick(item)">
              <b-image :src="item.pic" mode="widthFix" />
            </view>
          </view>
        </footer-bar>
      </template>
    </template>

    <template v-else>
      <!-- list -->
      <view v-if="listLength" class="article-list">
        <template v-for="(item, index) in list">
          <template v-if="parent_id === 5">
            <view :key="index" class="article-item" @click="articleClick(item)">
              <b-image class-name="pic" :src="item.cover" mode="aspectFill" />
              <view class="sub-item">
                <view class="article-item_title">{{ item.title }}</view>
                <view class="article-item_num">
                  <view class="view">
                    <b-image class-name="icon" src="/static/images/material/icon_view.png" mode="aspectFit" :is-asset="true" />
                    {{ item.browse_num | formatNumber(2, true) }}
                  </view>
                  <b-image v-if="item.study_status === 1" class-name="btn" src="/static/images/material/btn_complete.png" mode="aspectFit" :is-asset="true" />
                  <b-image v-else class-name="btn" src="/static/images/material/btn_study.png" mode="aspectFit" :is-asset="true" />
                </view>
              </view>
            </view></template>
          <template v-else>
            <view v-if="index===0" :key="index" class="article-item first" @click="articleClick(item)">
              <b-image class-name="img" :src="item.cover" mode="aspectFill" />
              <view class="article-item_title">{{ item.title }}</view>
              <view class="article-item_num">
                <view>{{ item.time_desc }}</view>
                <view class="view">
                  <b-image class-name="icon" src="/static/images/material/icon_view.png" mode="aspectFit" :is-asset="true" />
                  {{ item.browse_num | formatNumber(2, true) }}
                </view>
              </view>
            </view>
            <view v-else :key="index" class="article-item" @click="articleClick(item)">
              <view class="sub-item">
                <view class="article-item_title">{{ item.title }}</view>
                <view class="article-item_num">
                  <view>{{ item.time_desc }}</view>
                  <view class="view">
                    <b-image class-name="icon" src="/static/images/material/icon_view.png" mode="aspectFit" :is-asset="true" />
                    {{ item.browse_num | formatNumber(2, true) }}
                  </view>
                </view>
              </view>
              <b-image class-name="img" :src="item.cover" mode="aspectFill" />
            </view>
          </template>

        </template>
      </view>
      <base-list-state :list-length="listLength" :list-query="listQuery" :list-state="listState" :list-empty="listEmpty" />
    </template>
  </base-page-view>
</template>
<script>
import horizontalList from '@/components/horizontalList/index'
import customModules from '@/components/customModules'
import footerBar from '@/components/footerBar'
import { debounce, getQueryString } from '@/utils/tools'
import { h5NavigateTo } from '@/utils/navigateTo'
import './index.scss'
export default {
  name: 'ArticleMaterial',
  components: {
    horizontalList,
    customModules,
    footerBar
  },
  data() {
    return {
      pageLoaded: false,
      parent_id: '', // 3: 走进碧选 4:创业故事 5:商学院
      categoryList: [],
      currentCategoryIndex: 0,
      tagList: [],
      currentTagIndex: 0,

      url: '',
      activity_id: '',
      activityConfig: {
        name: ''
      },
      activityData: {
        modules: []
      },
      scrollTop: 0,

      listQuery: {
        category_id: '',
        page_no: 1,
        page_size: 10
      },
      listState: {
        loading: false,
        more: true
      },
      listEmpty: {
        type: 'empty_list',
        text: '暂无数据'
      },
      list: []
    }
  },
  computed: {
    listLength() { // 由于微信小程序无法自动更新base-list-state组件,故采用computed
      return this.list.length
    }
  },
  onLoad(options) {
    this.parent_id = Number(options.id) || ''
    this.$setNavTitle(options.title)
    if (this.parent_id) {
      this.fetchData()
    }
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop
  },
  onPullDownRefresh() {
    this.listQuery.page_no = 1
    this.fetchData()
  },
  onReachBottom: debounce(function() {
    if (this.listState.more && !this.listState.loading) {
      this.listQuery.page_no++
      this.fetchArticleData()
    }
  }, 500),
  methods: {
    async fetchData() {
      this.listState.loading = true
      const res = await this.$api.materialApi.getSubCategoryAll({ parent_id: this.parent_id })
      if (res.success) {
        this.categoryList = res.data || []
      }
      this.initCategory()
    },
    // 初始化category_id
    initCategory() {
      if (this.categoryList.length) {
        if (!(this.currentCategoryIndex < this.categoryList.length)) {
          this.currentCategoryIndex = 0
        }
        const currentCategory = this.categoryList[this.currentCategoryIndex]
        if (currentCategory.have_url) {
          this.url = currentCategory.direct_url
          this.tagList = []
          this.listQuery.category_id = ''
        } else {
          this.url = ''
          this.tagList = currentCategory.child_categorys || []

          if (this.tagList.length) {
            const currentTag = this.tagList[this.currentTagIndex]
            if (currentTag.have_url) {
              this.url = currentTag.direct_url
              this.listQuery.category_id = ''
            } else {
              this.url = ''
              this.listQuery.category_id = currentTag.id
            }
          } else {
            this.listQuery.category_id = currentCategory.id
          }
        }
      } else {
        this.listQuery.category_id = this.parent_id
      }

      if (this.listQuery.category_id) {
        this.listQuery.page_no = 1
        this.fetchArticleData()
      } else {
        this.initUrlData()
      }
    },
    // 初始化链接数据
    initUrlData() {
      if (this.url.indexOf('pagesDetail/template/index') > -1) {
        this.activity_id = getQueryString('id', this.url)
        this.fetchUrlData()
      } else {
        this.endPageLoad()
        h5NavigateTo(this.url)
      }
    },
    // 获取链接数据
    async fetchUrlData() {
      const res = await this.$api.homeApi.getActivity({
        activity_id: decodeURIComponent(this.activity_id)
      })
      if (res.success && res.data) {
        this.activityData = JSON.parse(res.data.activity.comment || '{ modules: [] }')
        delete res.data.activity.comment
        this.activityConfig = res.data.activity
      }
      this.endPageLoad()
    },
    // 获取文章列表
    async fetchArticleData() {
      this.listState.loading = true
      const res = await this.$api.materialApi.getCategoryMaterial({ ...this.listQuery })
      if (this.listQuery.page_no === 1) {
        this.list = []
      }
      if (res.success) {
        const list = res.data || []
        this.list = this.list.concat(list)
        this.listState.more = list.length === this.listQuery.page_size
      }
      this.endPageLoad()
    },
    // 结束页面加载状态
    endPageLoad() {
      setTimeout(() => {
        this.pageLoaded = true
        this.listState.loading = false
        uni.stopPullDownRefresh()
      }, 500)
    },
    // 点击顶部分类
    categoryClick(index) {
      if (this.currentCategoryIndex === index) {
        return
      }
      this.currentCategoryIndex = index
      this.currentTagIndex = 0
      this.list = []
      this.initCategory()
    },
    // 点击tag
    tagClick(index) {
      if (this.currentTagIndex === index) {
        return
      }
      this.currentTagIndex = index
      this.initCategory()
    },
    // 点击文章
    async articleClick(item) {
      if (this.token) {
        let res

        if (this.parent_id === 5) {
          // 商学院文章
          res = await this.$api.materialApi.toStudy({ id: item.id })
          if (res.success) {
            // 去学习成功
            item.study_status = 1
          }
        }

        // 数据统计："countType": "操作类型：1 ~ 分享统计，2 ~ 下载统计，3 ~ 浏览统计，4 ~ 复制统计,5 ~ 点赞统计",
        res = await this.$api.materialApi.materialCount({ count_type: 3, id: item.id, user_id: this.userInfo.uid })
        if (res.success) {
          // 浏览成功
          item.browse_num++
        }

        switch (item.content_type) {
          case 1:
            this.$navigateTo(`/pagesMaterial/article/detail?id=${item.id}&pid=${this.parent_id}&title=${item.category_desc}`)
            break
          case 2:
            h5NavigateTo(item.content)
            break

          default:
            break
        }
      } else {
        this.$navigateTo('/pages/login/index')
      }
    }
  }
}
</script>
